package com.wxx.attendance;

import com.wxx.push.WeChatPush;
import com.wxx.util.CrawlerUtil;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.Calendar;
import java.util.List;

/**
 * 考情打卡
 */
public class AttendanceProcess {
    private static ChromeDriver webDriver;
    private static String userName = "";
    private static String password = "";
    private static String weChatUserId = "";

    static {
        CrawlerUtil.configChromeDriver();
        ChromeOptions option = new ChromeOptions();
//        option.addArguments("headless");    // 不打开浏览器窗口，直接在后台执行任务
        webDriver = new ChromeDriver(option);
    }

    private void start() {
        webDriver.get("https://oa.sheincorp.cn/wui/main.jsp?logintype=1");
        webDriver.findElement(By.xpath("//input[@name='loginid']")).sendKeys(userName);
        webDriver.findElement(By.xpath("//input[@name='userpassword']")).sendKeys(password);
        try {
            webDriver.findElement(By.xpath("//button[contains(text(),'登录')]")).click();
            webDriver.findElement(By.xpath("//div[contains(text(),'考勤')]")).click();
        } catch (Exception e) {
            log("账号或者密码错误");
            exit();
            return;
        }
        WebElement targetElement = webDriver.findElement(By.xpath("//span[contains(text(),'考勤日报明细')]"));

        Actions actions = new Actions(webDriver);
        actions.moveToElement(targetElement).click(targetElement).perform();

        try {
            webDriver.switchTo().frame("mainFrame");
            WebElement tableElement = new WebDriverWait(webDriver, Duration.ofSeconds(30))
                    .until(ExpectedConditions.elementToBeClickable(By.xpath("//table[@class='ListStyle']")));

            String today = new SimpleDateFormat("yyyy-MM-dd").format(System.currentTimeMillis());
            int currentHour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
            List<WebElement> elementList = tableElement.findElement(By.tagName("tbody")).findElements(By.xpath(".//tr[@style='vertical-align: middle;']"));
            for (WebElement element: elementList) {
                List<WebElement> tdElementList = element.findElements(By.tagName("td"));
                String date = tdElementList.get(7).getText();
                if (today.equals(date)) {
                    // 是今天的打卡数据，果果打卡了，就会显示具体的打卡时间，否则显示空胡总恶化旷工等
                    String shangban = tdElementList.get(10).getText();
                    String shangbanIsNormal = tdElementList.get(11).getText();
                    String xiaban = tdElementList.get(12).getText();
                    String xiabanIsNormal = tdElementList.get(13).getText();

                    String pushText = "";
                    if (!shangban.startsWith(today) && !shangbanIsNormal.equals("正常") && !xiaban.startsWith(today) && !xiabanIsNormal.equals("正常") && currentHour >= 17) {
                        // 上下班卡都没打
                        pushText = "你今天的上下班卡都没打，请及时打卡";
                    } else if (!shangban.startsWith(today) && !shangbanIsNormal.equals("正常")) {
                        // 没有打过上班卡
                        pushText = String.format("你今天上班卡没有按时打卡，请及时打卡。今天的打卡情况：上班打卡时间:%s     下班打卡时间:%s", shangban, xiaban);
                    } else if (!xiaban.startsWith(today) && !xiabanIsNormal.equals("正常") && currentHour >= 17) {
                        // 没有打过下班卡，设置14点之后才判断下班卡
                        pushText = String.format("你今天下班卡没有按时打卡，请及时打卡。今天的打卡情况：上班打卡时间:%s     下班打卡时间:%s", shangban, xiaban);
                    }
                    log(String.format("打卡数据：%s  上班打卡时间:%s     下班打卡时间:%s", date, shangban, xiaban));
                    if (!pushText.isEmpty()) {
                        log("开始推送：" + pushText);
//                        WeChatPush.pushText(pushText);
                        WeChatPush.pushText(pushText, weChatUserId);
                    } else {
                        log("今天打卡正常");
                    }
                    return;
                }
            }
            log("打卡正常");
        } catch (Exception e) {
            exit();
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        try {
            if (args.length < 3) {
                log("请输入工号和密码和微信id");
                exit();
                return;
            }
            userName = args[0];
            password = args[1];
            weChatUserId = args[2];
            new AttendanceProcess().start();
            exit();
        } catch (Exception e) {
            log("错误了");
            e.printStackTrace();
        }
    }

    private static void log(String message) {
        if (message == null || message.isEmpty())
            return;
        String time = new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss").format(System.currentTimeMillis());
        System.out.println(String.format("%s    %s", time, message));
    }

    private static void exit() {
        if (webDriver != null) {
            webDriver.quit();
        }
        System.exit(0);
    }

}